import { defineStore } from 'pinia'
import { useOtherStore } from './other'
import { debounce } from 'lodash'
export interface Item {
  name: string
  quantity: number
  id: number
}
export interface IUser {
  name: string
  id: number
}
declare module '@pinia/plugin-debounce' {
  export interface Config {
    Debounce: typeof debounce
  }
}
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    name: '',
    user: {} as IUser,
    items: [
      {
        id: 1,
        name: 'clother',
        quantity: 2,
      },
      {
        id: 2,
        name: 'food',
        quantity: 3,
      },
      {
        id: 3,
        name: 'iphone13',
        quantity: 1,
      },
    ] as Item[],
    hasChange: false,
  }),
  getters: {
    doubleCount(state): number {
      return state.count * 2
    },
    doubleCountPlusOne(): number {
      return this.doubleCount + 1
    },
    composeGetter(state) {
      const otherStore = useOtherStore()
      return state.count + otherStore.count
    },
    getGoodsById(state) {
      return (id: number) => state.items.find((item) => item.id === id)
    },
  },
  actions: {
    increment() {
      console.log('increment')
      this.count++
    },
    async getUserInfoByRegister(username: string, pwd: string) {
      try {
        console.log('getUserInfoByRegister')
        this.user = (await getUserInfo(username, pwd)) as IUser
        this.hasChange = true
      } catch (error) {
        return error
      }
    },
  },
  debounce: {
    getUserInfoByRegister: 1000,
    increment: [
      300,
      {
        // options passed to debounce
        isImmediate: true,
      },
    ],
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'myCounter',
        storage: localStorage,
        paths: ['user', 'count'],
      },
    ],
  },
})
async function getUserInfo(username: string, pwd: string) {
  console.log('getUserInfo', username, pwd)
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        name: 'dsy',
        id: 1,
      })
    }, 1000)
  })
}
// import {ref,computed} from 'vue'
// export const useCounterStore = defineStore('counter',() => {
//   const count = ref(0)
//   const doubleCount = computed(() => count.value * 2)
//   function increment(){
//     count.value++
//   }
//   return {count,doubleCount,increment}
// })
